package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public String login(User user) {
        String password = user.getPassword();
        byte[] bytes = password.getBytes();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5DigestAsHex);
        System.out.println(md5DigestAsHex);
        User userDB = userMapper.findUserByUP(user);
        if (userDB==null){
            return null;
        }
        String token = UUID.randomUUID().toString();
        return token;
    }

    @Override
    public PageResult findUserList(PageResult pageResult) {
        long total = userMapper.findTotal();
        String query = pageResult.getQuery();
        int start = (pageResult.getPageNum()-1)*pageResult.getPageSize();
        int size = pageResult.getPageSize();
        List<User> rows = userMapper.findUserList(query,start,size);
        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateStatus(User user) {
        user.setUpdated(new Date());
        userMapper.updateStatus(user);
    }

    @Override
    @Transactional
    public void addUser(User user) {
        String password = user.getPassword();
        byte[] bytes = password.getBytes();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5DigestAsHex);
        user.setStatus(true).setCreated(new Date()).setUpdated(user.getCreated());
        userMapper.insert(user);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        user.setUpdated(new Date());
        userMapper.updateById(user);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }
}
